package com.rp.system.po;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.raptor.entity.BaseModel3;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.rp.common.utils.RpUtil;

/**
 * 用户
 * @author HuangJian
 *
 */
@Entity
@Table(name="RP_SYSTEM_USERS")
public class User extends BaseModel3 implements UserDetails{
	
	private static final long serialVersionUID = 176375280896670027L;
	
	private String username;		//用户名
	private String password;		//密码
	private String realname;		//姓名
	private boolean enabled;		//boolean类型的激活状态
	private String enabled2;		//String类型的激活状态
	private String remark;			//备注
	private String headImg;			//头像
	
	private String organId;
	private String organName;
	
	private Integer errorLoginCount = 0;			//失败的登录次数
	private String errorLoginInitTimestamp = "0";	//第一次到达登录最大限制数时的时间戳
	
	/*
	 * 是否是超级管理员，使用MD5加密的串(A6105C0A611B41B08F1209506350279E)来标识超管，加密的原文为yes
	 */
	private String superAdmin = "0";		
	
	//private List<Role> roles;		//对应角色
	
	private String roleId;
	private String roleName;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

	public String getRealname() {
		return realname;
	}
	public void setRealname(String realname) {
		this.realname = realname;
	}

	@JsonIgnore
	public boolean isEnabled() {
		return enabled;
	}
	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	public String getEnabled2() {
		return enabled2;
	}
	public void setEnabled2(String enabled2) {
		this.enabled2 = enabled2;
	}

	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}

	public String getHeadImg() {
		return headImg;
	}
	public void setHeadImg(String headImg) {
		this.headImg = headImg;
	}
	
	public String getOrganId() {
		return organId;
	}
	public void setOrganId(String organId) {
		this.organId = organId;
	}
	public String getOrganName() {
		return organName;
	}
	public void setOrganName(String organName) {
		this.organName = organName;
	}
	public Integer getErrorLoginCount() {
		return errorLoginCount;
	}
	public void setErrorLoginCount(Integer errorLoginCount) {
		this.errorLoginCount = errorLoginCount;
	}
	
	public String getErrorLoginInitTimestamp() {
		return errorLoginInitTimestamp;
	}
	public void setErrorLoginInitTimestamp(String errorLoginInitTimestamp) {
		this.errorLoginInitTimestamp = errorLoginInitTimestamp;
	}
	
	public String getSuperAdmin() {
		return superAdmin;
	}
	public void setSuperAdmin(String superAdmin) {
		this.superAdmin = superAdmin;
	}
	
	/*@ManyToMany(
			fetch = FetchType.LAZY, 
			cascade = {CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
	@JoinTable(
			name = "RP_SYSTEM_USER_ROLE", 
			joinColumns = { @JoinColumn(name = "user_id") }, 
			inverseJoinColumns = { @JoinColumn(name = "role_id") })
	public List<Role> getRoles() {
		return roles;
	}

	public void setRoles(List<Role> roles) {
		this.roles = roles;
	}*/
	
	
	public String getRoleId() {
		return roleId;
	}
	public void setRoleId(String roleId) {
		this.roleId = roleId;
	}
	public String getRoleName() {
		return roleName;
	}
	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}
	
	/**
	 * 获取当前登录用户
	 * @return
	 */
	@Transient
	public static User getCurrentUser(){
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if(principal instanceof UserDetails){
			return ((User)principal);
		}
		return null;
	}
	
	/**
	 * 判断当前登录用户是否是超级管理员
	 * @return
	 */
	/*@Transient
	public static boolean isSuperUser(){
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		User user = ((User)principal);
		
		Role role = user.getRole();
		if(role.getSuperRole().equals("1")){
			return true;
		}
		
		return false;
	}*/
	
	@JsonIgnore
	@Transient
	public Collection<GrantedAuthority> getAuthorities() {
		/*List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for (Role role : roles) {
			List<Authority> auths = role.getAuthorities();
			for (Authority auth : auths) {
				boolean repe = false;//是否有重复的权限
				for(GrantedAuthority ga : authorities) {
					if(ga.getAuthority().equals(auth.getCode())){
						repe = true;
						break;
					}
				}
				//如果没有重复，则添加
				if(!repe){
					authorities.add(new GrantedAuthorityImpl(auth.getCode()));
				}
			}
		}*/
		
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		if(!RpUtil.isNullOrEmpty(roleId)){
			List<Record> dbAuths = Db.use("rpDb")
					.find("select a.code from rp_system_authorities a left join rp_system_role_authority ra on a.id = ra.authority_id where role_id = '"+roleId+"'");
			for (Record auth : dbAuths) {
				authorities.add(new GrantedAuthorityImpl(auth.getStr("code")));
			}
		}else{
			throw new AuthenticationServiceException("此用户未分配关联角色，无法进行登录！");
		}
		return authorities;
	}

	@Transient
	public boolean isAccountNonExpired() {
		return true;
	}

	@Transient
	public boolean isAccountNonLocked() {
		return true;
	}

	@Transient
	public boolean isCredentialsNonExpired() {
		return true;
	}
	
	public boolean equals(Object obj) {
		if (obj instanceof UserDetails) {
			UserDetails ud = (UserDetails) obj;
			if (ud.getUsername().equals(this.getUsername())) {
				return true;
			}
		}
		return false;
	}
	
	public String toString(){
		return new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE)
		.toString();
	}

}
